package com.app.shop.controller.wx;

import com.app.shop.controller.system.BaseController;
import com.app.shop.entity.weixin.WxPayDto;
import com.app.shop.entity.weixin.WxPayInfo;
import com.app.shop.service.weixin.WeixinService;
import com.app.shop.util.ApiRest;
import com.app.shop.util.Constant;
import com.app.shop.util.SignUtil;
import com.app.shop.util.weixin.GetWxOpenId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.util.SortedMap;
import java.util.TreeMap;


/**
 * 支付模块
 *
 * @author chenliwei
 * @version v1.0 2017-11-5
 */
@Controller
public class WxPayController extends BaseController {
    private static final Logger LOG = LoggerFactory.getLogger(WxPayController.class);

    @Autowired
    public WeixinService weixinService;



    /**
     * @Title
     * @Description (通过CODE,type获取OPENID)
     * @author Garfield Miao
     * @date 2019年25月20日
     * @upAuthor Garfield Miao
     * @update 2019年25月20日 
     */
    @ResponseBody
    @RequestMapping(value = "/api/weixin/getOpenIdByType", method = RequestMethod.GET)
    public ApiRest getOpenIdByType(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "code", required = true) String code) throws  Exception{

        WxPayDto dto= new GetWxOpenId().getOpenIdByType(code);

        return new ApiRest(Constant.REST_SUCCESS_CODE, Constant.SUCCESS_MESSAGE, dto);


    }


    /**
     * @Title
     * @Description (获取微信预支付ID)
     * @author Garfield Miao
     * @date 2019年25月34日
     * @upAuthor Garfield Miao
     * @update 2019年25月34日
     */
    @ResponseBody
    @RequestMapping(value = "/api/weixin/getPrepayid", method = RequestMethod.POST)
    public ApiRest getPrepayid(
            HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "openId", required = true) String openId,
            @RequestParam(value = "orderId", required = true) Integer orderId,
            @RequestParam(value = "amount", required = true) String amount,
            @RequestParam(value = "sign", required = true) String sign,
            @RequestParam(value = "body", required = true) String body)throws Exception{
        //MD5Y验证
        SortedMap<String, String> finalsign = new TreeMap<String, String>();
        finalsign.put("openId", openId);
        if(null==orderId){
            finalsign.put("orderId","");
        }else{
            finalsign.put("orderId",orderId+"");
        }
        finalsign.put("amount", amount);
        finalsign.put("body", body);

        if(!sign.equals(SignUtil.signMD5(finalsign))){
            return new ApiRest(Constant.REST_FAIL_CODE,"签名错误" , null);
        }



        String spbill_create_ip = request.getHeader("x-forwarded-for");
        if (spbill_create_ip == null || spbill_create_ip.length() == 0 || "unknown".equalsIgnoreCase(spbill_create_ip)) {
            spbill_create_ip = request.getHeader("Proxy-Client-IP");
        }
        if (spbill_create_ip == null || spbill_create_ip.length() == 0 || "unknown".equalsIgnoreCase(spbill_create_ip)) {
            spbill_create_ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (spbill_create_ip == null || spbill_create_ip.length() == 0 || "unknown".equalsIgnoreCase(spbill_create_ip)) {
            spbill_create_ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (spbill_create_ip == null || spbill_create_ip.length() == 0 || "unknown".equalsIgnoreCase(spbill_create_ip)) {
            spbill_create_ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (spbill_create_ip == null || spbill_create_ip.length() == 0 || "unknown".equalsIgnoreCase(spbill_create_ip)) {
            spbill_create_ip = request.getRemoteAddr();
        }
        if(spbill_create_ip.contains(",")){
            spbill_create_ip = spbill_create_ip.split(",")[0];
            LOG.info("spbill_create_ip------:"+spbill_create_ip);
        }

        WxPayInfo wxPayInfo = weixinService.getPrepayid(openId,orderId,amount,spbill_create_ip,body);
        if(null==wxPayInfo){
            return new ApiRest(Constant.REST_FAIL_CODE,"获取预支付ID失败" , null);
        }else{
            return new ApiRest(Constant.REST_SUCCESS_CODE, Constant.SUCCESS_MESSAGE, wxPayInfo);
        }


    }


    /**
     * @Title
     * @Description (微信回调)
     * @author Garfield Miao
     * @date 2019年25月35日
     * @upAuthor Garfield Miao
     * @update 2019年25月35日
     */
    @ResponseBody
    @RequestMapping(value = "/api/weixin/payCallBack", method = RequestMethod.POST)
    public void payCallBack(
            HttpServletRequest request, HttpServletResponse response
           )throws Exception{

        LOG.info("WeixinpayCallBack begin!");
        Long time = System.currentTimeMillis();
        String inputLine;
        String notityXml = "";
        String resXml = "";
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            request.getReader().close();
            Long time1 = System.currentTimeMillis();
            LOG.info("payCallBackReaderTIME:"+(time1-time));
        } catch (Exception e) {
            e.printStackTrace();
        }
//		LOG.info("微信支付回调报文"+notityXml);
        resXml=weixinService.payCallBack(notityXml);
//		LOG.info("微信支付回调数据结束");

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
        Long time2 = System.currentTimeMillis();
        LOG.info("payCallBackTIME:"+(time2-time));

    }







}